package com.neo.upload.controller;

import com.neo.common.BaseResult;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;

@Controller
@RequestMapping(path = "/api/upload")
public class UploadAPIController {
    /**
     * 上传路径
     */
    // @Value("${server.UPLOAD_PATH}")
    private String UPLOAD_PATH = "/Users/git/images2";

    /**
     * 图片上传，需要赋值读写权限-->
     *
     * @author wangsong
     * @date 2019年6月14日 下午2:31:49
     * @return
     */
    @PostMapping(value = "/uploadImage", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    @ApiOperation(value = "上传图片", notes = "上传图片", httpMethod = "POST")
    @ApiResponses(value = { @ApiResponse(code = 200, message = "上传成功！"), @ApiResponse(code = 500, message = "上传失败！") })
    @ResponseBody
    public BaseResult uploadImage(HttpServletRequest request,
            @ApiParam(value = "图片", required = true) MultipartFile image) {
        try {
            InputStream inputStream = image.getInputStream();

            // 获取图片的文件名
            String fileName = image.getOriginalFilename();
            // 获取图片的扩展名
            String extensionName = fileName.substring(fileName.indexOf("."));
            // 新的图片文件名 = 获取时间戳+"."图片扩展名
            String newFileName = String.valueOf(System.currentTimeMillis()) + extensionName;
            String name = newFileName;

            // 目录路径
            Path directory = Paths.get(UPLOAD_PATH);
            // 判断目录是否存在，不存在创建
            if (!Files.exists(directory)) {
                Files.createDirectories(directory);
            }

            // 判断文件是否存在,存在删除
            if (Files.exists(directory.resolve(name))) {
                File file = new java.io.File(UPLOAD_PATH + "/" + name);
                file.delete();
            }

            // 拷贝文件
            // filepath: UPLOAD_PATH + "/" + name;
            Files.copy(inputStream, directory.resolve(name));

            // url路径
            // 获得客户端发送请求的完整url
            String url = request.getRequestURL().toString();
            // 获得去除接口前的url
            String urlVal = url.replace("/uploadImage", "/getImage");

            String path = urlVal + "/" + name;
            return BaseResult.successWithData(path);
        } catch (Exception e) {
            return BaseResult.failWithCodeAndMsg(200, "上传失败");
        }
    }

    /**
     * 使用流将图片输出
     *
     * @param response
     * @param name
     * @throws IOException
     */
    @GetMapping("/getImage/{name:.+}")
    public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException {
        response.setContentType("image/jpeg;charset=utf-8");
        response.setHeader("Content-Disposition", "inline; filename=girls.png");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(Files.readAllBytes(Paths.get(UPLOAD_PATH).resolve(name)));
        outputStream.flush();
        outputStream.close();
    }

}